
package com.epam.android.taining.day7;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.format.Time;
import android.util.Log;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Service check if current time is the expected time, and if success - send
 * broadcast and stop the service.
 * 
 * @author Natallia_Kukharchyk
 */
public class AlertsService extends Service {

  private static long UPDATE_INTERVAL = 1 * 60 * 1000;

  private static long DELAY_INTERVAL = 0;

  private int hour;

  private int minute;

  private final Timer timer = new Timer();

  public static final String CUSTOM_INTENT = "com.epam.android.taining.day7.MY_INTENT_RECEIVER";

  @Override
  public IBinder onBind(Intent arg0) {
    return null;
  }

  @Override
  public void onCreate() {
    super.onCreate();
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    if (timer != null) {
      timer.cancel();
    }
    Log.i(getClass().getSimpleName(), "Timer stopped...");
  }

  @Override
  public void onStart(Intent intent, int startid) {
    // get data from intent
    if (null != intent) {
      hour = intent.getIntExtra("hours", 0);
      minute = intent.getIntExtra("minutes", 0);
    }
    startCustomService();

  }

  /*
   * starting the service
   */
  private void startCustomService() {
    timer.scheduleAtFixedRate(

    new TimerTask() {

      @Override
      public void run() {
        doServiceWork();
        try {
          Thread.sleep(UPDATE_INTERVAL);
        } catch (InterruptedException e) {
          Log.e(getClass().getSimpleName(), "AlertService InterruptedException" + e.toString());
        }
      }
    }, DELAY_INTERVAL, UPDATE_INTERVAL);

    Log.i(getClass().getSimpleName(), "AlertService Timer started....");
  }

  /**
   * Check if time is up - send broadcast. Actually, for such type of issues
   * (like alerts) no need to perform such action every minute, but in this case
   * I did it just for demonstration.
   */
  private void doServiceWork() {
    Time currentTime = new Time();
    currentTime.setToNow();
    if (hour == currentTime.hour && minute == currentTime.minute) {
      Intent i = new Intent();
      i.setAction(CUSTOM_INTENT);
      getApplicationContext().sendBroadcast(i);
      // stop server when time is up
      stopSelf();
    }

  }
}
